import { menu } from '../../../app/decorator';
import { app } from '../../../app/app';

const { ccclass, property } = cc._decorator;

@ccclass
@menu(__filename)
export default class MoveToAction extends cc.Component {
    @property
    private _target: cc.Node = null;
    @property({ type: cc.Node })
    get target() { return this._target || this.node || null; }
    set target(value) { this._target = value; }

    @property(cc.Node)
    startNode: cc.Node = null;

    @property(cc.Node)
    endNode: cc.Node = null;

    @property
    time = 1;

    private _finishCb: Function = null;

    protected onLoad() {
        this.target.active = false;
        this.node.on('play', this.play, this);
    }

    public play(finish: Function, time?: number) {
        this.target.active = true;

        this._finishCb && this._finishCb();
        this._finishCb = finish;

        let startPos = app.lib.cocos.node.convertNodeToParentSpaceAR(this.target, this.startNode);
        let endPos = app.lib.cocos.node.convertNodeToParentSpaceAR(this.target, this.endNode);

        this.target.x = startPos.x;
        this.target.y = startPos.y;

        this.target.stopAllActions();
        this.target.runAction(cc.sequence(
            cc.moveTo(time || this.time, endPos.x, endPos.y),
            cc.callFunc(function () {
                this.target.active = false;
                this._finishCb && this._finishCb();
                this._finishCb = null;
            }, this)
        ));
    }
}